package com.peng.leetcode.tree;

/**
 * IsBalanced2
 * 剑指 Offer 55 - II. 平衡二叉树
 * https://leetcode.cn/problems/ping-heng-er-cha-shu-lcof/
 * <p>
 * Created on 2022/12/5
 *
 * @author lupeng
 */
public class IsBalanced2 {
    public boolean isBalanced(TreeNode root) {
        if (root == null) {
            return true;
        }
        dfs(root);
        return ans;
    }

    boolean ans = true;

    int dfs(TreeNode n) {
        if (n == null || !ans) {
            return 0;
        }
        int l = dfs(n.left);
        int r = dfs(n.right);
        if (Math.abs(l - r) > 1 && ans) {
            ans = false;
        }
        return Math.max(l, r) + 1;
    }

}
